import path from 'path'
import multer from 'multer'
import Express from 'express'
import fs from "fs/promises"
export const UploadRouter = Express.Router();
const storage = multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,path.resolve(import.meta.dirname,'../static/upload'))

    },
    filename:function(req,file,cb){
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
        const ext = path.extname(file.originalname);
        cb(null,file.fieldname + '-' + uniqueSuffix + ext);
    }
})
const upload = multer({storage:storage});

UploadRouter.post('/',upload.single('file'),async(req,res)=>{ 
    res.json({
        code:0,
        msg:"上传成功",
        data:'http://localhost:8090/'+req.file.filename
    })
})

UploadRouter.delete('/',async(req,res)=>{
    const name = req.body.name;
    const filename = name.replace("http://localhost:8090/","");
    //对应的路径删除文件
    await fs.unlink(path.resolve(import.meta.dirname,"../static/upload",filename))
    res.json({
        code:0,
        msg:"删除成功"
    })
})